package com.mengdie.shuidi.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.event.PayEvent;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.OrderEntity;
import com.mengdie.shuidi.ui.interfaces.PayHelper;
import com.mengdie.shuidi.ui.interfaces.PayView;
import com.mengdie.shuidi.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/8/31 10:44
 * 邮箱：hqy_xz@126.com
 */

public class PackageTypeActivity extends BaseActivity implements PayView {


    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.tv_type_name)
    TextView mTvTypeName;
    @Bind(R.id.tv_type_back)
    TextView mTvTypeBack;
    @Bind(R.id.tv_type_account)
    TextView mTvTypeAccount;
    @Bind(R.id.tv_type_num)
    TextView mTvTypeNum;
    @Bind(R.id.tv_type_coupon)
    TextView mTvTypeCoupon;
    @Bind(R.id.tv_pay_save)
    TextView mTvPaySave;
    @Bind(R.id.et_pay_code)
    EditText mEtPayCode;
    @Bind(R.id.tv_type_money)
    TextView mTvTypeMoney;
    @Bind(R.id.tv_type_alipay_money)
    TextView mTvTypeAlipayMoney;
    @Bind(R.id.tv_type_alipay_coupon)
    TextView mTvTypeAlipayCoupon;
    @Bind(R.id.iv_type_alipay)
    ImageView mIvTypeAlipay;
    @Bind(R.id.iv_type_wx)
    ImageView mIvTypeWx;
    @Bind(R.id.rl_type_coupon)
    RelativeLayout mRlTypeCoupon;

    private String payType = "1";
    private String mPackageId = "";
    private String type = "";
    private OrderEntity orderInfo;

    private PayHelper mPayHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_type);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mPackageId = bundle.getString(UIHelper.PACKAGE_ID);
            type = bundle.getString(UIHelper.TYPE);
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void init() {
        mPayHelper = new PayHelper(PackageTypeActivity.this, this);
        mTvGenericTitle.setText("订单提交");
        mIvTypeAlipay.setVisibility(View.VISIBLE);
        getBusGateway("");
    }


    @OnClick({R.id.rl_generic_back, R.id.tv_type_back, R.id.tv_type_coupon, R.id.tv_pay_save
            , R.id.rl_type_alipay, R.id.rl_type_wx, R.id.tv_pay_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_generic_back:
            case R.id.tv_type_back:
                finish();
                break;
            case R.id.tv_type_coupon:
                mRlTypeCoupon.setVisibility(View.VISIBLE);
                mTvTypeCoupon.setVisibility(View.GONE);
                break;
            case R.id.tv_pay_save:
                String coupon = mEtPayCode.getText().toString();
                if (EmptyUtils.isNotEmpty(coupon)) {
                    getBusGateway(coupon);
                } else {
                    ToastUtil.showToast("优惠券不能为空");
                }
                break;
            case R.id.rl_type_alipay:
                mIvTypeAlipay.setVisibility(View.VISIBLE);
                mIvTypeWx.setVisibility(View.GONE);
                payType = "1";
                updateMoney(payType);
                break;
            case R.id.rl_type_wx:
                mIvTypeAlipay.setVisibility(View.GONE);
                mIvTypeWx.setVisibility(View.VISIBLE);
                payType = "2";
                updateMoney(payType);
                break;
            case R.id.tv_pay_submit:
                String money = mTvTypeMoney.getText().toString();
                String codes = mEtPayCode.getText().toString();
                getOrderId(codes, money);
                break;
        }
    }

    private void updateMoney(String payType) {
//        mTvTypeAlipayMoney.setVisibility(payType.equals("1") ? View.VISIBLE : View.GONE);
//        if (payType.equals("1")) {
//            mTvTypeMoney.setText("￥" + (Double.valueOf(orderInfo.getSumPrice()) - 1));
//        } else {
            mTvTypeMoney.setText("￥" + orderInfo.getSumPrice());
//        }
    }

    /**
     * 获取订单信息
     *
     * @param coupon
     */
    private void getBusGateway(final String coupon) {
        Map<String, String> map = new HashMap<>();
        map.put("req_type", "1");
        map.put("balance_flag", "false");
        map.put("coupon", coupon);
        map.put("pak_id", mPackageId);
        map.put("exec_type", "add_time");
        map.put("num", "1");
        map.put("terminal_type", "Android");
        map.put("add_terminal", "0");
        map.put("username", MDUserMgr.getInstance().getUsername());
        JSONObject json = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(PackageTypeActivity.this))
                .post(AppContext.getInstance().getPayUrl() + "core/bus/gateway")
                .upJson(json)
                .tag("order")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type oderType = new TypeToken<BaseModel<OrderEntity>>() {
                        }.getType();

                        BaseModel<OrderEntity> orderBase;
                        try {
                            orderBase = gson.fromJson(s, oderType);
                        } catch (JsonSyntaxException e) {
                            orderBase = gson.fromJson(s, BaseModel.class);
                        }
                        if (orderBase.getRet().equals("0")) {
                            updateOrderInfo(orderBase.getData());
                        } else {
                            ToastUtil.showToast(orderBase.getMsg());
                        }
                    }
                });
    }


    private void updateOrderInfo(OrderEntity order) {
        orderInfo = order;
        mTvTypeName.setText(type);
        mTvTypeAccount.setText(MDUserMgr.getInstance().getShowUsername());
        mTvTypeNum.setText(order.getSumTerminal() + "");
//        if (payType.equals("1")) {
//            mTvTypeMoney.setText("￥" + (Double.valueOf(orderInfo.getSumPrice()) - 1));
//        } else {
            mTvTypeMoney.setText("￥" + orderInfo.getSumPrice());
//        }
    }

    /**
     * 获取订单ID
     *
     * @param coupon
     * @param money
     */
    private void getOrderId(String coupon, String money) {
        Map<String, String> map = new HashMap<>();
        map.put("req_type", "2");
        map.put("balance_flag", "false");
        map.put("money", money.substring(1, money.length()));
        map.put("coupon", coupon);
        map.put("pak_id", mPackageId + "");
        map.put("exec_type", "add_time");
        map.put("num", "1");
        map.put("terminal_type", "Android");
        map.put("add_terminal", "0");
        map.put("username", MDUserMgr.getInstance().getUsername());
        JSONObject json = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(PackageTypeActivity.this))
                .post(AppContext.getInstance().getPayUrl() + "core/bus/gateway")
                .upJson(json)
                .tag("order")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type oderType = new TypeToken<BaseModel<OrderEntity>>() {
                        }.getType();

                        BaseModel<OrderEntity> orderBase;
                        try {
                            orderBase = gson.fromJson(s, oderType);
                        } catch (JsonSyntaxException e) {
                            orderBase = gson.fromJson(s, BaseModel.class);
                        }
                        if (orderBase.getRet().equals("0")) {
                            mPayHelper.setOrder(orderBase.getData().getOrder(), payType);
                        } else {
                            ToastUtil.showToast(orderBase.getMsg());
                        }
                    }
                });

    }

    @Override
    public void paySucc() {
        MDUserMgr.getInstance().setLastTime("1");
        finish();
    }

    @Override
    public void payFial() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PayEvent event) {
        finish();
    }
}
